<script setup lang="ts">
import { ref } from 'vue'

// 图片地址
const imageUrl = ref(
  'https://ts4.cn.mm.bing.net/th?id=ORMS.31dfd56909b246ca78307c5f9c2ade20&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=0.8999999761581421&p=0',
)

// 保存图片到相册的方法
const saveImageToAlbum = async () => {
  // 如果是在移动设备上（例如在手机浏览器或原生 app 环境）
  if (typeof navigator !== 'undefined' && navigator.share) {
    // 现代浏览器支持 Share API 来分享文件
    try {
      const response = await fetch(imageUrl.value)
      const blob = await response.blob()
      const file = new File([blob], 'downloaded-image.jpg', { type: 'image/jpeg' })

      await navigator.share({
        files: [file],
        title: 'Download Image',
        text: 'Here is an image you requested.',
      })

      alert('Image shared successfully!')
    } catch (err) {
      console.error('Error while sharing the image:', err)
      alert('Failed to share the image.')
    }
  } else {
    // 针对浏览器无法直接保存图片的情况，我们通常会提供下载链接
    const a = document.createElement('a')
    a.href = imageUrl.value
    a.download = 'image.jpg'
    a.click()
  }
}
</script>

<template>
  <view class="w-full h-screen center">
    <view class="w-96% h-40%">
      <img class="w-full h-full" style="object-fit: contain" :src="imageUrl" alt="image" />
    </view>
    <wd-tabbar fixed shape="round" bordered safeAreaInsetBottom placeholder>
      <wd-tabbar-item @click="saveImageToAlbum" title="保存" icon="home"></wd-tabbar-item>
    </wd-tabbar>
  </view>
</template>

<style scoped lang="scss">
.center {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
